//
//  NetSyncViewController.m
//  iMoney
//
//  Created by Sean McGrail on 1/29/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "NetSyncViewController.h"
#import "iMoneyAppDelegate.h"


#define kServiceIdentifier		@"_money._tcp."


@interface NSNetService (BrowserViewControllerAdditions)
- (NSComparisonResult) localizedCaseInsensitiveCompareByName:(NSNetService*)aService;
@end

@implementation NSNetService (BrowserViewControllerAdditions)
- (NSComparisonResult) localizedCaseInsensitiveCompareByName:(NSNetService*)aService {
	return [[self name] localizedCaseInsensitiveCompare:[aService name]];
}
@end


@implementation NetSyncViewController


@synthesize netServiceBrowser;
@synthesize services;
@synthesize net;



- (id)init
{
	if (self = [super init]) {
		
		self.tabBarItem.image = [UIImage imageNamed:@"sync.png"];
		self.title = @"Sync";
		
		self.view =[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
		
		
		UIImageView* bImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gradientBackground.png"]];
		[self.view addSubview:bImage];
		[bImage release];
		
		browsing= NO;
		
		syncButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
		syncButton.frame = CGRectMake(10, self.view.frame.size.height-120, 300, 30);
		[syncButton setTitle:@"Sync" forState:UIControlStateNormal];
		syncButton.backgroundColor = [UIColor clearColor];
		[syncButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal ];
		[syncButton addTarget:self action:@selector(syncPressed:) forControlEvents:UIControlEventTouchDown];
	
		[self.view addSubview:syncButton];
	
	}
	
	return self;
}



-(IBAction) syncPressed: (id)sender
{

	// open a dialog options
	actionSheet = [[UIActionSheet alloc] initWithTitle:@"Services\n\n\n\n\n\n\n\n\n\n"
															 delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
													otherButtonTitles:nil];
	
	

	serviceTable = [[UITableView alloc] initWithFrame:CGRectMake(15, 35, 290, 200)
											 style: UITableViewStyleGrouped];
	serviceTable.backgroundColor = [UIColor clearColor];
	[serviceTable setDataSource:self];
	[serviceTable setDelegate:self];
	[actionSheet addSubview:serviceTable];
	

	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	
	UITabBarController* tbc = ((iMoneyAppDelegate*)[[UIApplication sharedApplication] delegate]).tabBarController;
	
	[actionSheet showInView:tbc.view];
	[actionSheet release];
			
	if(services == nil)
		services = [[NSMutableArray alloc] init];
	else
		[services removeAllObjects];
		
		
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	[self searchForServicesOfType:kServiceIdentifier inDomain:@"local"];
			
	browsing= YES;
	
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	//NSLog([NSString stringWithFormat:@"%d", buttonIndex]);
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[netServiceBrowser stop];
	browsing= NO;
	
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)viewDidLoad {

}


- (void)dealloc {
	
	[syncButton release];
	[net release];
	[netServiceBrowser release];
	[services release];
	[serviceTable release];
	//[netIndicator release];
    [super dealloc];
}


//------- table stuiff

- (NSInteger)numberOfSectionsInTableView:(UITableView *)newTableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)newTableView numberOfRowsInSection:(NSInteger)section {
	// If there are no services and searchingForServicesString is set, show one row to tell the user.
	NSUInteger count = [self.services count];
	
	if(count == 0)
		count = 1;
	
	return count;
}

- (UITableViewCell *)tableView:(UITableView *)newTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *tableCellIdentifier = @"UITableViewCell";
	UITableViewCell *cell = (UITableViewCell *)[newTableView dequeueReusableCellWithIdentifier:tableCellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCellIdentifier] autorelease];
	}
	
	if([self.services count] == 0)
	{
		cell.textLabel.text = @"Searcing for services ...";
		cell.textLabel.textColor = [UIColor blackColor];
		return cell;
	}
		
	
	NSNetService *service = [self.services objectAtIndex:indexPath.row];
	cell.textLabel.text = [service name];
	cell.textLabel.textColor = [UIColor blackColor];
	
	return cell;
}

- (NSIndexPath *)tableView:(UITableView *)newTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	// Ignore the selection if there are no services as the searchingForServicesString cell
	// may be visible and tapping it would do nothing
	if ([self.services count] == 0)
		return nil;
	
	//try to resolve service
	//[netIndicator startAnimating];
	
	NSNetService* netservice = [self.services objectAtIndex:indexPath.row];
	netservice.delegate = self;
	[netservice resolveWithTimeout:10]; //ten seconds

	[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	
	if(overlay == nil){
		overlay = [OverlayView loadingViewInView:self.view: @"Starting Net Service"];
	}
	
	
	return indexPath;
}


//-----------------------------


// Creates an NSNetServiceBrowser that searches for services of a particular type in a particular domain.
// If a service is currently being resolved, stop resolving it and stop the service browser from
// discovering other services.
- (BOOL)searchForServicesOfType:(NSString *)type inDomain:(NSString *)domain {
		
	NSNetServiceBrowser *aNetServiceBrowser = [[NSNetServiceBrowser alloc] init];
	if(!aNetServiceBrowser) {
        // The NSNetServiceBrowser couldn't be allocated and initialized.
		return NO;
	}
	
	aNetServiceBrowser.delegate = self;
	self.netServiceBrowser = aNetServiceBrowser;
	[aNetServiceBrowser release];
	[self.netServiceBrowser searchForServicesOfType:type inDomain:domain];
	
	[serviceTable reloadData];
	return YES;
}


// New service was found
- (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didFindService:(NSNetService *)netService moreComing:(BOOL)moreServicesComing {
	
	[self.services addObject:netService];

	// If more entries are coming, no need to update UI just yet
	if ( moreServicesComing ) {
		return;
	}
	
	[serviceTable reloadData];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


// Service was removed
- (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didRemoveService:(NSNetService *)netService moreComing:(BOOL)moreServicesComing {
	
}


//found a service
-(void)netServiceDidResolveAddress:(NSNetService *)service {
    
	[OverlayView setScreenText:@"Syncing Data"];
	
	net = [[NetHandler alloc] initWithNetService:service :self];
	
	[OverlayView setScreenText:@"Sending Data"];
	[net sendXML:[[iMoneyAppDelegate getMoneyState] getDataXML:YES]];
}

-(void)netService:(NSNetService *)service didNotResolve:(NSDictionary *)errorDict {
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	[OverlayView setScreenText:@"Resolve Timed Out"];
	
	[overlay
	 performSelector:@selector(removeView)
	 withObject:nil
	 afterDelay:2];
}


- (void) progress: (NSString*) message
{
	[OverlayView setScreenText:message];
	
}
- (void) error: (NSString*) message
{
	[OverlayView setScreenText:message];
	
	[overlay
	 performSelector:@selector(removeView)
	 withObject:nil
	 afterDelay:2];
	
	[net release];
	net = nil;

}
- (void) done
{	
	[overlay
	 performSelector:@selector(removeView)
	 withObject:nil
	 afterDelay:.2];
	
	//[netIndicator stopAnimating];
	[net sendXML:@"ok"];
	
	[services removeAllObjects];
	[serviceTable reloadData];
	
	//((iMoneyAppDelegate*)[[UIApplication sharedApplication] delegate]).tabBarController.selectedIndex = 0;
	
	[net release];
	net = nil;
}

//---------------


@end

